/*******************************************************************************
 * Copyright (c) 2013 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
/**
 * 
 */
package com.niannian.activity;

import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.niannian.adapter.ListDialogAdapter;
import com.niannian.dialog.SimpleListDialog;
import com.niannian.dialog.YesNoDialog2;
import com.niannian.dialog.SimpleListDialog.onSimpleListItemClickListener;
import com.niannian.dialog.YesNoDialog2.onSimpleOnClicklListener;
import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MyTextWatcher;
import com.niannian.util.UmengPage;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 
 * 添加联系人
 * 
 * @author shengl
 * 
 */
public class AddFamilyMemberActivity extends BaseActivity {
	private RelativeLayout rl_add_family_member;

	LinearLayout ll_add_member_phone;
	EditText reg_member_phone;
	Button btn_member_add;

	String phone = "";
	String name = "";
	private static final int REQUEST_CONTACT = 10;

	private int ACTION_TYPE = 0;// 0表示查看家庭成员，1表示邀请家庭成员
	private String[] item;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_family_member);
		initData();
		initView();
		setLister();
		initTopView();
	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("添加亲友");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);

		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myfinish();
			}
		});
	}

	private void initView() {

		rl_add_family_member = (RelativeLayout) findViewById(R.id.rl_add_family_member);

		ll_add_member_phone = (LinearLayout) findViewById(R.id.ll_add_member_phone);
		reg_member_phone = (EditText) findViewById(R.id.reg_member_phone);
		reg_member_phone.addTextChangedListener(textWatcher);
		btn_member_add = (Button) findViewById(R.id.btn_member_add);

	}

	private void setLister() {

		rl_add_family_member.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				MobclickAgent.onEvent(AddFamilyMemberActivity.this, UmengPage.ADD_FRIEND_FROM_CONTACTS);
				requetContact();
			}
		});

		btn_member_add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				MobclickAgent.onEvent(AddFamilyMemberActivity.this, UmengPage.add_friend_by_phone);
				name = "";
				phone = reg_member_phone.getText().toString().trim();
				if (phone.length() != 11) {
					Common.tip(AddFamilyMemberActivity.this, "请输入您的11位手机帐号");
					return;
				}
				if (ACTION_TYPE == 0 || ACTION_TYPE == 3) {
					new GetSmsContent().init(AddFamilyMemberActivity.this, null, true, "请稍等...").execute();
				} else {
					fromBook();
				}

			}
		});

	}

	private void initData() {
		try {
			ACTION_TYPE = getIntent().getIntExtra("ACTION_TYPE", 0);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private MyTextWatcher textWatcher = new MyTextWatcher() {

		@Override
		public void onFocusChange(View view, boolean hasFocus) {
		};

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			String acct = reg_member_phone.getText().toString().trim();
			if (!Common.empty(acct)) {
				btn_member_add.setEnabled(true);
			} else {
				btn_member_add.setEnabled(false);
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CONTACT:
			if (data == null) { // Toast.makeText(getApplicationContext(),
								// "你没有选择联系人", Toast.LENGTH_LONG).show();
			} else {
				phone = "";
				name = "";
				Uri contactURI = data.getData();
				Cursor cursor = getContentResolver().query(contactURI, null, null, null, null);
				while (cursor.moveToNext()) {
					StringBuilder sb = new StringBuilder();
					// 获取联系人的ID
					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

					// 获取联系人的姓名
					name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
					String pString = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
					if (Integer.parseInt(pString) == 0) {
						Common.tip(AddFamilyMemberActivity.this, "手机号格式错误");
					} else {
						try {
							Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
									ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
							item = new String[phoneCursor.getCount()];
							int i = 0;
							while (phoneCursor.moveToNext()) {
								phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
								phone = phone.replaceAll(" ", "");
								phone = phone.replaceAll("-", "");
								item[i] = phone;
								i++;
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
						try {
							if (Common.empty(item)) {
								phone = contactURI.toString().split("lookup")[1].split("/")[1].split("i")[1].substring(0, 11);
								if (ACTION_TYPE == 0 || ACTION_TYPE == 3) {
									new GetSmsContent().init(AddFamilyMemberActivity.this, null, true, "请稍等...").execute();
								} else {
									fromBook();
								}
							} else {
								if (item.length > 1) {
									initListDialog();
								} else {
									if (ACTION_TYPE == 0 || ACTION_TYPE == 3) {
										new GetSmsContent().init(AddFamilyMemberActivity.this, null, true, "请稍等...").execute();
									} else {
										fromBook();
									}
								}
							}
						} catch (Exception e) {
							// TODO: handle exception
						}
					}

				}
			}
			break;

		default:
			break;
		}
	}

	public void requetContact() {
		Intent contactIntent = new Intent();
		contactIntent.setAction(Intent.ACTION_PICK);
		contactIntent.setData(ContactsContract.Contacts.CONTENT_URI);
		startActivityForResult(contactIntent, REQUEST_CONTACT);
	}

	public void sendSMS(String phone, String smsData) {
		Uri uri = Uri.parse("smsto:" + phone);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", smsData);
		startActivity(it);
	}

	String sms_content = "";

	protected class GetSmsContent extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(AddFamilyMemberActivity.this, "操作失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			try {
				int retCode = paramJSONObject.getInt("code");
				if (retCode == ErrorCode.OK) {
					sms_content = paramJSONObject.getString("sms_content");

					JSONArray jsonArray = new JSONArray();
					JSONObject jsonObject = paramJSONObject.getJSONObject("data");
					jsonArray.put(jsonObject);

					databaseapi.updateMyFamily(userInfoManager.id, jsonObject);

					int gid = jsonObject.getInt("id");
					Intent intent = new Intent();
					intent.putExtra("gid", gid);
					setResult(RESULT_OK, intent);

					initDialog3();
				} else {
					Common.tip(AddFamilyMemberActivity.this, paramJSONObject.getString("msg"));
				}
			} catch (Exception e) {

			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			return nnSyncApi.addFamilyMember(phone, name);
		}
	}

	YesNoDialog2 tip3;

	private void initDialog3() {

		tip3 = new YesNoDialog2(AddFamilyMemberActivity.this, "您已成功添加  " + ("".equals(name) ? phone : name) + "  为家庭成员. 记得发送短信告诉Ta, 以便Ta能正常访问家庭与您互动");

		tip3.setHideCancel();
		tip3.setConfimButtonText("确  定");

		tip3.setOnConfimClickListener(new onSimpleOnClicklListener() {

			@Override
			public void onClick() {
				tip3.dismiss();
				if (ACTION_TYPE == 3) {
					openActivity(FamilyMemberActivity.class);
				}
				myfinish();
			}
		});
		tip3.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				sendSMS(phone, sms_content);
				Common.tip(AddFamilyMemberActivity.this, "操作成功");
				if (ACTION_TYPE == 3) {
					openActivity(FamilyMemberActivity.class);
				}
				myfinish();
			}
		});
		tip3.show();
	}

	SimpleListDialog listDialog;

	private void initListDialog() {
		listDialog = new SimpleListDialog(AddFamilyMemberActivity.this);
		listDialog.setAdapter(new ListDialogAdapter(AddFamilyMemberActivity.this, item));

		listDialog.serOnSimpleListItemClikListener(new onSimpleListItemClickListener() {
			@Override
			public void onItemClick(int postion) {

				listDialog.dismiss();
				phone = item[postion];
				if (ACTION_TYPE == 0 || ACTION_TYPE == 3) {
					new GetSmsContent().init(AddFamilyMemberActivity.this, null, true, "请稍等...").execute();
				} else {
					fromBook();
				}

			}
		});
		listDialog.show();
	}

	private void fromBook() {
		Intent intent = new Intent();
		int from = 2;// 表示来自通讯录
		intent.putExtra("from", from);
		intent.putExtra("phone", phone);
		intent.putExtra("name", name);
		setResult(RESULT_OK, intent);
		myfinish();
	}
}
